package com.mzy;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;

public class Code02_FourOperations {


    public static int add(int num1, int num2) {

        int sum = num1;
        while (num2 != 0) {
            sum = num1 ^ num2; // 无进位相加信息
            num2 = (num1 & num2) << 1; // 进位信息
            num1 = sum;
        }
        return sum;
    }

    public static int subtract(int a, int b) {
        return add(a, add(~b, 1));
    }


    public static int multi(int a, int b) {
        int result = 0;

        while (b != 0) {
            if ((b & 1) != 0) {
                result = add(result, a);
            }
            a <<= 1;
            b >>>= 1;
        }
        return result;
    }

    public static int div(int a, int b) {
        if (b == 0) {
            throw new ArithmeticException("/ by zero");
        }
        int x = isNeg(a) ? negNum(a) : a;
        int y = isNeg(b) ? negNum(b) : b;
        int result = 0;

        for (int i = 30; i >= 0; i = subtract(i, 1)) {
            if ((x >> i) >= y) {
                result |= 1 << i;
                x = subtract(x, y << i);
            }
        }
        return isNeg(a) ^ isNeg(b) ? negNum(result) : result;
    }

    public static boolean isNeg(int num) {
        return num < 0;
    }

    public static int negNum(int num) {
        return ~num + 1;
    }

    public static int recursion(int num1, int num2) {
        if (num2 == 0) return num1;

        return recursion(num1 ^ num2, (num1 & num2) << 1);
    }


    public int divide(int dividend, int divisor) {
        if (dividend == Integer.MIN_VALUE && divisor == Integer.MIN_VALUE) {
            return 1;
        } else if (divisor == Integer.MIN_VALUE) {
            return 0;
        } else if (dividend == Integer.MIN_VALUE) {
            if(divisor == 1) {
                return Integer.MAX_VALUE;
            }
            int ans = div(dividend + 1, divisor);
            return div((dividend - (ans * divisor)), divisor) + ans;
        } else {
            return div(dividend, divisor);
        }
    }

    public static void main(String[] args) {
        // System.out.println(subtract(3, 10));
        // System.out.println(multi(10, 2));

        // for (int i = 0; i < 1000000; i++) {
        //     int a = randomValue(10000);
        //     int b = randomValue(1000);
        //     if (div(a, b) != (a / b)) {
        //         System.out.println(a + "," + b);
        //     }
        // }
        System.out.println(Math.abs(Integer.MIN_VALUE));
        System.out.println(div(Integer.MIN_VALUE, -1));
    }

    public static int randomValue(int maxValue) {
        return (int) (Math.random() * maxValue) + 1;
    }
}
